import time
import json
import sys
import os


def id_to_mac(device_id):
    return ':'.join([device_id[i - 1] + device_id[i] for i in range(len(device_id)) if i % 2 != 0])


def combine_info(com_info, node_id):
    timeArray = time.localtime(com_info[0])
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    info = '''
            Device Information 
        Device MAC: %s,
        ========================= 
        CPU Core: %s,
        CPU Utilization: %s%%,
        ========================= 
        Total Memory (MB): %.2f, 
        Used Memory (MB): %.2f, 
        Memory Utilization (MB): %s%%,
        =========================
        Total Disk (MB): %.2f, 
        Used Disk (MB): %.2f, 
        Disk Utilization (MB): %s%%, 
        =========================
        Network Received (KB) : %.2f, 
        Network Sent (KB): %.2f,
        =========================
        Collected Time :    %s, 
        Current Time:       %s
    ''' % (node_id, com_info[1], com_info[2],
           com_info[3], com_info[4], com_info[5],
           com_info[6], com_info[7], com_info[8],
           com_info[9], com_info[10], otherStyleTime,
           time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
    return info


def show(device_id: str):
    with open('data/commit_index', 'r') as cf:
        commit_index = int(cf.readline())
    with open('data/log.json', 'r') as lf:
        full_data = json.load(lf)
    log_data = full_data[commit_index - 1]['info'][device_id]
    os.system('cls' if os.name == 'nt' else 'clear')
    print('\r', combine_info(log_data, id_to_mac(device_id)), end='', flush=True)
    sys.stdout.flush()


def show_multiple(device_list):
    with open('data/commit_index', 'r') as cf:
        commit_index = int(cf.readline())
    with open('data/log.json', 'r') as lf:
        full_data = json.load(lf)
    log_data = full_data[commit_index - 1]['info']
    huge_info = ''
    for device_id in device_list:
        huge_info = huge_info + combine_info(log_data[device_id], id_to_mac(device_id)) + '\n'
    os.system('cls' if os.name == 'nt' else 'clear')
    print('\r', huge_info, end='', flush=True)
    sys.stdout.flush()


if __name__ == '__main__':
    with open('data/configure.json', 'r') as f:
        data = json.load(f)
        node_list = [data['id']] + list(data['peers'].keys())
    for index, x in enumerate(node_list):
        print(index, x)
    node_index = int(input('Please input node index. -1 means show all.\n'))
    while True:
        time.sleep(0.2)
        try:
            if node_index == -1:
                show_multiple(node_list)
            else:
                show(node_list[node_index])
        except:
            pass
